/*
8.1.1. Create a module for working with DOM. The module should have the following functionality
 - Add DOM element to parent element given by selector
 - Remove element from the DOM  by given selector
 - Attach event to given selector by given event type and event handler
 - Add elements to buffer, which appends them to the DOM when their count for some selector becomes 100
The buffer contains elements for each it gets
Get elements by CSS selector
The module should reveal only the methods
 */

var domModule = (function() {
    var buffer = document.createDocumentFragment();
    var selectorsCounters = {};

    function appendChild(element, elementToAppendWithinSelector) {
        var parent = document.querySelector(elementToAppendWithinSelector);
        parent.appendChild(element);
    }

    function removeChild(parentSelector, elementToRemoveSelector) {
        var parentElement = document.querySelector(parentSelector);

        var elementToRemove = parentElement.querySelector(elementToRemoveSelector);

        elementToRemove.parentNode.removeChild(elementToRemove);

        /*
        // I'm leaving this function for further usage (backup)
        function deepCopyDOMObject(sourceObjectForCopy)
        {
            if (typeof (sourceObjectForCopy) !== 'object') {
                return sourceObjectForCopy;
            }
            else {
                var duplicatedObject = {};

                for (var prop in sourceObjectForCopy) {
                    duplicatedObject[prop] = deepCopyDOMObject(sourceObjectForCopy[prop]);
                }

                return duplicatedObject;
            }
        }
        */
    }

    function addHandler(elementToAttachEventSelector, typeOfEvent, eventHandler) {
        var elementToAttachEvent = document.querySelector(elementToAttachEventSelector);
        elementToAttachEvent.addEventListener(typeOfEvent, eventHandler);
    }

    function appendToBuffer(elementToAppendWithinSelector, elementForAppending) {
        buffer.appendChild(elementForAppending);

        if (selectorsCounters.elementToAppendWithinSelector === undefined) {
            selectorsCounters.elementToAppendWithinSelector = 1;
        }
        else {
            selectorsCounters.elementToAppendWithinSelector++;

            if (selectorsCounters.elementToAppendWithinSelector === 100) {
                document.querySelector(elementToAppendWithinSelector).appendChild(buffer);

                selectorsCounters = {};
                buffer = document.createDocumentFragment();
            }
        }
    }

    return {
        appendChild: appendChild,
        removeChild: removeChild,
        addHandler: addHandler,
        appendToBuffer: appendToBuffer
    };
}());